package labb2.del2;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * @author Mikko Puustinen
 * @version 0.3, 2007-sep-26
 */
public class UserInterface {
    private CollectionOfBooks bookcollection;
    private Scanner sc;

    /**
     * UserInterface
     */
    public UserInterface() {
        bookcollection = new CollectionOfBooks();
        sc = new Scanner(System.in);
        menu();
    }

    /**
     * main.
     *
     * @param args arguments. Not used.
     */
    public static void main(String[] args) {
        new UserInterface();
    }

    /**
     * Menu.
     */
    public void menu() {
        String line;
        String[] commands;
        boolean run = true;
        System.out.println(info());
        do {
            printMenu();
            try {
                line = sc.nextLine();
            } catch (Exception e) {
                line = "novalue";
            }
            commands = line.split(" ", 2);
            switch (MenuChoices.toChoice(commands[0].toLowerCase())) {
                case add:
                    addBook(commands);
                    break;
                case searchi:
                    searchISBN(commands);
                    break;
                case searcht:
                    searchTitle(commands);
                    break;
                case searcha:
                    searchAuthor(commands);
                    break;
                case list:
                    listAllBooks();
                    break;
                case save:
                    saveFile(commands);
                    break;
                case load:
                    loadFile();
                    break;
                case help:
                    System.out.println(helpInfo());
                    break;
                case info:
                    System.out.println(info());
                    break;
                case exit:
                    exit();
                    break;
                default:
                    System.out.println("Usage: [command] [optional]\nType \"help\" for full commands list");
            }

        } while (run);
    }

    /**
     * Prints the menu.
     */
    public void printMenu() {
        System.out.print("\nCommand: ");
    }

    /**
     * Add a Book to the collection.
     *
     * @param commands command to be executed.
     */
    public void addBook(String[] commands) {
        String title;
        String authors;
        String isbn;
        int edition;
        double price;
        String[] splittedAuthors;
        boolean run = true;

        if (commands.length > 1)
            title = commands[1];
        else {
            try {
                System.out.print("Title: ");
                title = sc.nextLine();
            } catch (Exception e) {
                System.out.println("Error while reading line.");
                return;
            }
        }
        do {
            System.out.println("Editing book: \"" + title + "\"");

            do {
                System.out.print("Authors [Separate with ;]: ");
                authors = sc.nextLine();
                splittedAuthors = authors.split(";");
            } while (authors.length() < 1);

            System.out.print("ISBN: ");
            isbn = sc.nextLine();

            try {
                System.out.print("Edition: ");
                edition = Integer.parseInt(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Error while reading edition.");
                return;
            }

            try {
                System.out.print("Price: ");
                price = Double.parseDouble(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Error while reading price.");
                return;
            }

            System.out.println("\nInformation:");
            System.out.println("Title: " + title + "\nAuthors: ");
            for (String str : splittedAuthors)
                System.out.println("\t" + str);
            System.out.println("ISBN: " + isbn);
            System.out.println("Edition: " + edition);
            System.out.println("Price: " + price + "\n");
            System.out.print("Do you want to add this information? (yes/no/exit): ");
            char c = sc.nextLine().charAt(0);
            if (c == 'y') {
                System.out.println("Information added!");
                bookcollection.addBook(title, splittedAuthors, isbn, edition, price);
                run = false;
            } else if (c == 'e')
                run = false;
        } while (run);
    }

    /**
     * Search for ISBN
     *
     * @param commands commands to be executed.
     */
    public void searchISBN(String[] commands) {
        String isbn;

        if (commands.length > 1)
            isbn = commands[1];
        else {
            System.out.print("Search for ISBN: ");
            try {
                isbn = sc.nextLine();
            } catch (Exception e) {
                System.out.println("Error while reading line.");
                return;
            }
        }

        showList(bookcollection.getBooksByISBN(isbn));
    }

    /**
     * Search for title
     *
     * @param commands commands to be executed.
     */
    public void searchTitle(String[] commands) {
        String title;

        if (commands.length > 1)
            title = commands[1];
        else {
            System.out.print("Search for title: ");
            try {
                title = sc.nextLine();
            } catch (Exception e) {
                System.out.println("Error while reading line.");
                return;
            }
        }

        showList(bookcollection.getBooksByTitle(title));
    }

    /**
     * Search for author
     *
     * @param commands commands to be executed.
     */
    public void searchAuthor(String[] commands) {
        String author;

        if (commands.length > 1)
            author = commands[1];
        else {
            System.out.print("Search for author: ");
            try {
                author = sc.nextLine();
            } catch (Exception e) {
                System.out.println("Error while reading line.");
                return;
            }
        }

        showList(bookcollection.getBooksByAuthor(author));
    }

    /**
     * Lists all books.
     */
    public void listAllBooks() {
        showList(bookcollection.getAllBooks());
    }

    /**
     * Saves the file
     *
     * @param commands commands
     */
    public void saveFile(String[] commands) {
        int error;

        if (commands.length > 1)
            error = bookcollection.saveToFile(commands[1]);
        else
            error = bookcollection.saveToFile();
        if (error < 0)
            System.out.println("Error while saving!");
        else {
            System.out.println("Saved collection!");
        }
    }

    /**
     * Converts a collection to a printable format.
     *
     * @param book list to show
     */
    private void showList(ArrayList<Book> book) {
        for (Book b : book) {
            System.out.println("Title: " + b.getTitle() + ", " + b.getEdition() + " ed.");
            System.out.println("Authors: ");
            for (Author a : b.getAuthors())
                System.out.println("\t" + a.getName());
            System.out.println("ISBN: " + b.getISBN());
            System.out.println("Price: " + b.getPrice() + "\n");
        }
    }

    /**
     * Load a file containing a collection of Books.
     * <p/>
     * Not implemented.
     */
    public void loadFile() {
        System.out.println("Not implemented");
    }

    /**
     * Creates a printer-friendly file.
     * <p/>
     * Not implemented.
     */
    public void print() {
        System.out.println("Not implemented");
    }

    /**
     * Exit the program.
     * <p/>
     * The list will be saved before the program terminates.
     */
    public void exit() {
        saveFile(new String[0]);
        System.exit(0);
    }

    /**
     * Show version info.
     *
     * @return version info
     */
    public String info() {
        return "mazbook v0.3 Console";
    }

    /**
     * Show a help menu containing all the possible commands.
     *
     * @return information regarding the commands of the program.
     */
    public String helpInfo() {
        return MenuChoices.help();
    }
}